package com.koal.conifg.security;


import com.koal.util.JwtTokenUtil;



import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt登录授权过滤器
 * @ClassName JwtAuthenticationTokenFilter
 * @Author LuoYQ
 **/

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    public static Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    @Autowired
    public UserDetailsService userDetailsService;
    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    public String tokenHeader;
    @Value("${jwt.tokenHead}")
    public String tokenHead;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String tokenAndHead = request.getHeader(this.tokenHeader);
        if (StringUtils.isEmpty(tokenAndHead) && !tokenAndHead.startsWith(this.tokenHead)) {
            LOGGER.error("传入的token为空或token格式不正确");
        }

        String token = tokenAndHead.substring(this.tokenHead.length());
        Claims claimsFromToken = jwtTokenUtil.getClaimsFromToken(token);
        if (claimsFromToken == null) {
            LOGGER.error("token解析失败");
        }
        String username = claimsFromToken.getSubject();
        //判断用户是否登录（是否在上下文中）,若为空，则添加。
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request,response);

    }
}
